package top.rushpeak.edu03.websocket.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import com.alibaba.fastjson.JSONObject;

import top.rushpeak.edu03.api.model.User;
import top.rushpeak.edu03.websocket.handler.MyWebSocketHandler;
import top.rushpeak.edu03.websocket.interceptor.MyHandShakeInterceptor;
import top.rushpeak.edu03.websocket.result.MsgResult;
import top.rushpeak.edu03.websocket.util.SessionManager;

@Configuration
@EnableWebMvc
@EnableWebSocket 
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {

		registry.addHandler(myWebSocketHandler(),"/webSocketServer").addInterceptors(new MyHandShakeInterceptor());  
        registry.addHandler(myWebSocketHandler(), "/webSocketServer/sockjs").addInterceptors(new MyHandShakeInterceptor()).withSockJS();
        AutoSend send = new AutoSend();
        send.setPriority(Thread.NORM_PRIORITY+1);
        send.start();
        
	}
	
	class AutoSend extends Thread{

		@Override
		public void run() {

			while(true){
				try {
					//TODO 轮询线程
					Thread.sleep(1000);
					//测试传对象
					MsgResult<User> res = new MsgResult<>();
					res.setCode("0");
					res.setMsgType("lunxun");
					res.setMessage("testlunxun");
					User user = new User();
					res.setData(user);
					for(WebSocketSession session:SessionManager.instance().get()){
						session.sendMessage(new TextMessage(JSONObject.toJSONString(res)));
					}
					
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		
		
	}
	
	
    @Bean
    public WebSocketHandler myWebSocketHandler() {
        return new MyWebSocketHandler();
    }

}
